package com.aliyun.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.oss.service.AliyunOssService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.UUID;

@Service
public class AliyunOssServiceImpl implements AliyunOssService {

    @Value("${aliyun.oss.endpoint}")
    private  String endpoint;         // "*** Provide OSS endpoint ***"
    @Value("${aliyun.oss.accesskeyid}")
    private  String accessKeyId;      // "*** Provide your AccessKeyId ***"
    @Value("${aliyun.oss.accesskeysecret}")
    private  String accessKeySecret;  // "*** Provide your AccessKeySecret ***"
    @Value("${aliyun.oss.bucketname}")
    private  String bucketName ;      // "*** Provide bucket name ***"

    public String ossFileUpload(String originalFileName, String modules, InputStream inputStream) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        //判断该bucketName是否存在
        if( !ossClient.doesBucketExist(bucketName) ){
            ossClient.createBucket(bucketName);
            //设置权限
            ossClient.setBucketAcl(bucketName , CannedAccessControlList.PublicRead);
        }
        // 上传文件流。
        //自定义文件上传名称: /study/2020/07/06/user.jpg
        String front = modules;
        String middle = new DateTime().toString("yyyy/MM/dd");
        //截取原始文件名的后缀
        String end = originalFileName.substring(originalFileName.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + end;

        String resultfileName = front+"/"+middle+"/"+fileName;

        ossClient.putObject(bucketName, resultfileName, inputStream);

        // 关闭OSSClient。
        ossClient.shutdown();

        //返回url : https://workplaces.oss-cn-shenzhen.aliyuncs.com/study/111.png
        String url ="https://" + bucketName +"." + endpoint + "/" + resultfileName;
        return url;
    }
}
